/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ubhave.sensormanager.ability;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.ESSensorManager;
import com.ubhave.sensormanager.ResourceTable;
import com.ubhave.sensormanager.SensorDataListener;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.pull.WifiData;
import com.ubhave.sensormanager.data.pull.WifiScanResult;
import com.ubhave.sensormanager.provider.WifiItemProvider;
import com.ubhave.sensormanager.sensors.SensorUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;
import ohos.wifi.WifiDevice;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

public class WifiAbility extends Ability implements SensorDataListener, Component.ClickedListener {

    private ListContainer listContainer;
    private Button startBtn;
    private Button stopBtn;
    private Text tip;
    private ESSensorManager sensorManager;
    private int subscriptionId;
    private List<WifiScanResult> list = new ArrayList<>();
    private WifiItemProvider wifiItemProvider;
    private SensorData mSensorData;
    private WifiDevice wifiManager;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        requestPermissionsFromUser(new String[]{"ohos.permission.LOCATION", "ohos.permission.GET_WIFI_INFO", "ohos.permission.SET_WIFI_INFO"}, 0);
        setUIContent(ResourceTable.Layout_ability_wifi);
        tip = (Text) findComponentById(ResourceTable.Id_tip);
        startBtn = (Button) findComponentById(ResourceTable.Id_start_btn);
        stopBtn = (Button) findComponentById(ResourceTable.Id_stop_btn);
        startBtn.setClickedListener(this);
        stopBtn.setClickedListener(this);
        wifiManager = WifiDevice.getInstance(getContext());

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_data_wifi);
        wifiItemProvider = new WifiItemProvider(list, this);
        listContainer.setItemProvider(wifiItemProvider);
        listContainer.setItemClickedListener((listContainer, component, position, id) -> {
            WifiScanResult item = (WifiScanResult) listContainer.getItemProvider().getItem(position);
            new ToastDialog(getContext())
                    .setText("clicked:" + item.getBssid())
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {
            try {
                sensorManager.unsubscribeFromSensorData(subscriptionId);
            } catch (ESException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDataSensed(SensorData data) {
        mSensorData = data;
        parseData(mSensorData);

    }

    private void parseData(SensorData data) {
        if (!(data instanceof WifiData)) {
            getContext().getUITaskDispatcher().asyncDispatch(() -> {
                tip.setText("数据异常!");
            });
            return;
        }
        WifiData wifiData = (WifiData) data;
        showBtList(wifiData);
    }

    private void showBtList(WifiData wifiData) {
        getContext().getUITaskDispatcher().delayDispatch(() -> {

            StringBuffer buffer = new StringBuffer();
            buffer.append("数据").append("\n");
            long timestamp = wifiData.getTimestamp();
            Date date = new Date();
            date.setTime(timestamp);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateString = dateFormat.format(date);

            buffer.append("senseStartTime: ").append(dateString).append("\n");
            buffer.append("senseStartTimeMillis: ").append(timestamp);

            tip.setText(buffer.toString());
            if (null != wifiData) {
                final ArrayList<WifiScanResult> wifiScanData = wifiData.getWifiScanData();
                if (null != wifiScanData && wifiScanData.size() > 0) {
                    list.clear();
                    list.addAll(wifiScanData);
                    wifiItemProvider.notifyDataChanged();

                } else {
                    tip.setText("暂无数据!");
                }
            } else {
                tip.setText("暂无数据!");
            }
        }, 1);
    }

    @Override
    public void onCrossingLowBatteryThreshold(boolean isBelowThreshold) {

    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_start_btn:
                try {
                    if (wifiManager.isWifiActive()) {
                        tip.setText("wifi搜索中,请勿继续操作...");
                        sensorManager = ESSensorManager.getSensorManager(getContext());
                        subscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_WIFI, this);
                        System.out.println(subscriptionId);
                    } else {
                        tip.setText("请先打开Wifi,再点击开始");
                    }

                } catch (ESException e) {
                    e.printStackTrace();
                }
                break;
            case ResourceTable.Id_stop_btn:
                if (sensorManager != null) {
                    try {
                        tip.setText("结束搜索!");
                        sensorManager.unsubscribeFromSensorData(subscriptionId);
                    } catch (ESException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        Optional<Sequenceable> sensorDataOptional = inState.getSequenceable("sensorData");
        if (sensorDataOptional.isPresent()) {
            mSensorData = (SensorData) sensorDataOptional.get();
            parseData(mSensorData);
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if (mSensorData != null) {
            outState.putSequenceableObject("sensorData", mSensorData);
        }
    }
}
